import React, {
  useState, useCallback, useEffect, useMemo, useRef,
} from 'react'
import {
  Text, View, Image, ImageBackground,
} from 'react-native'
import EStyleSheet from 'react-native-extended-stylesheet'
import Images from '@IMAGE'
import { PauseModal, PauseLimitModal, FinishModal } from '@COMPONENTS/modal/HomeModal'
import Button from '@COMPONENTS/button/Button'
import DeviceMaintenance from '@COMPONENTS/modal/DeviceMaintenance'
import BleDeviceFunctionality from '@UTILS/BleDeviceFunctionality'
import Toast from '@COMPONENTS/Toast'
import { DeviceState } from '@CONSTANTS/BleConstants'
import { useAppDispatch, useAppSelector } from '@REDUX/store'
import { actions } from '@REDUX/reducer/home'
import { useNavigation } from '@react-navigation/native'
import Storage, { StorageKey } from '@UTILS/Storage'
import Api from '@API'
import AnalyticsUtil, { ANALYTICS_EVENT } from '@UTILS/AnalyticsUtil'

const TOTAL_SECOND = 45 * 60
const minTreatmentTimeInSeconds = 1800
const treatmentDefaultTimeInSeconds = 2700
const imgObj = {
  ready: Images.home.notStart,
  inprogress: Images.home.start,
  pause: Images.home.notStart,
}

const Connected: React.FC = () => {
  const { deviceData, deviceData: { flags: { isInNoLoadState } } } = useAppSelector((state) => state.home)
  const { DeviceUUID } = useAppSelector((state) => state.user.user)
  const navigation = useNavigation()
  console.log('deviceData', deviceData)
  const dispatch = useAppDispatch()
  const state = useMemo(() => {
    if (deviceData.state === DeviceState.Idle) {
      return 'ready'
    }
    if (deviceData.state === DeviceState.Treatment) {
      return 'inprogress'
    }
    return 'pause'
  }, [deviceData.state])
  const [pauseLimit, setPauseLimit] = useState(false)
  const [isFinish, setFinish] = useState(false)
  const [showDeviceMaintenance, setShowDeviceMaintenance] = useState(false)
  const [strength, setStrength] = useState(deviceData.treatmentConfiguredIntensityInPercentage)
  const countDisabled = state === 'ready'
  const buttonDisabled = ['ready', 'pause'].includes(state)
  const buttonIcon = countDisabled ? Images.home.iconReady : Images.home.iconPause
  const buttonText = countDisabled ? '开始' : '暂停'
  const bleDevice = useMemo(() => new BleDeviceFunctionality(), [])
  const pauseCount = 3 - deviceData.numberOfPauseTreatmentsLeft// 暂停了几次
  const isPause = deviceData.state === 'Pause'
  // eslint-disable-next-line max-len
  const leftTreatment = Math.floor((deviceData.treatmentTimeLeftInSeconds + treatmentDefaultTimeInSeconds - minTreatmentTimeInSeconds) / treatmentDefaultTimeInSeconds)// 剩余疗程数
  const leftBody = isInNoLoadState && deviceData.state === DeviceState.Treatment

  const apiRef:any = useRef()
  apiRef.current = (ActivityType: string) => {
    Api.addActivity({
      DeviceId: DeviceUUID,
      ActivityType,
      Intensity: strength,
      DeviceResponse: deviceData,
      DeviceMinutes: deviceData.treatmentElapsedTimeInSeconds,
    })
  }
  const onEnd = useCallback(
    () => {
      AnalyticsUtil.onEvent(ANALYTICS_EVENT.tap_end_treatment.eventId)
      setPauseLimit(false)
      setFinish(true)
      bleDevice.stopTreatment()
      apiRef.current('End')
    },
    [bleDevice],
  )
  const onContinue = useCallback(
    () => {
      AnalyticsUtil.onEvent(ANALYTICS_EVENT.tap_continue_treatment.eventId)
      setPauseLimit(false)
      bleDevice.resumeTreatment()
      Toast.info('治疗已恢复')
      apiRef.current('Resume')
    },
    [bleDevice],
  )
  const onFinish = useCallback(
    () => {
      setFinish(false)
      bleDevice.stopTreatment()
      apiRef.current('End')
    },
    [bleDevice],
  )
  const onTimeEnd = useCallback(() => {
    bleDevice.stopTreatment()
    apiRef.current('End')
  }, [bleDevice])

  // 改变强度
  const strengthPress = (number:number) => {
    let newStrength = strength + number
    if (newStrength < 0) {
      newStrength = 0
    }
    if (newStrength > 100) {
      newStrength = 100
    }
    setStrength(newStrength)
    bleDevice.setIntensity(newStrength)
    apiRef.current('IntensityChange')
  }

  const { m: minute, s: second } = useMemo(() => {
    const count = TOTAL_SECOND - deviceData.treatmentElapsedTimeInSeconds
    if (count === 0) {
      onTimeEnd()
    }
    return ({
      m: String(Math.floor(count / 60)).padStart(2, '0'), // 剩余分钟数
      s: String(Math.floor(count % 60)).padStart(2, '0'), // 剩余秒数
      remainingSeconds: count, // 剩余的总秒数
    })
  }, [deviceData.treatmentElapsedTimeInSeconds, onTimeEnd])

  const buttonPress = () => {
    if (state === 'ready') {
      AnalyticsUtil.onEvent(ANALYTICS_EVENT.tap_start_treatment.eventId)
      // 开始治疗 开始计时
      bleDevice.startTreatment(12)
    }
    if (state === 'inprogress') {
      AnalyticsUtil.onEvent(ANALYTICS_EVENT.tap_pause_treatment.eventId)
      // 暂停计时 弹出暂停弹窗
      if (pauseCount + 1 > 3) {
        setPauseLimit(true)
        return
      }
      bleDevice.pauseTreatment()
    }
  }

  useEffect(() => {
    bleDevice.readDeviceStatus().then((res) => {
      dispatch(actions.setDeviceData(res))
    })
    bleDevice.addReadDeviceStatusListener((res) => {
      dispatch(actions.setDeviceData(res))
    })
    return () => {
      bleDevice.removeReadDeviceStatusListener()
    }
  }, [bleDevice, dispatch])

  useEffect(() => {
    navigation.setOptions({
      // eslint-disable-next-line react/no-unstable-nested-components
      headerRight: () => (
        <Text style={styles.headerRight}>
          {leftTreatment === 0 ? '15个疗程已用完' : `剩余${leftTreatment}个疗程`}
        </Text>
      ),
    })
  }, [navigation, leftTreatment])

  useEffect(() => {
    async function showMaintenance() {
      let connectCount = await Storage.get(StorageKey.connectCount)
      connectCount = connectCount || 0
      const deviceMaintenance = await Storage.get(StorageKey.deviceMaintenance)
      if (!deviceMaintenance && connectCount > 1) {
        setShowDeviceMaintenance(true)
      }
    }
    showMaintenance()
  }, [])

  useEffect(() => {
    if ([DeviceState.Error, DeviceState.Pause].includes(deviceData.state)) {
      const ActivityType = DeviceState.Pause === deviceData.state ? 'Pause' : 'Error'
      apiRef.current(ActivityType)
    }
  }, [deviceData.state])

  return (
    <View style={styles.page}>
      {leftBody && (
      <View style={styles.errorBox}>
        <Image source={Images.home.iconError} />
        <Text style={styles.error}>请确保保护膜已被移除，或电极与你的皮肤接触</Text>
      </View>
      )}

      <ImageBackground source={imgObj[state]} style={styles.imgBox}>
        <View style={styles.textBox}>
          {!countDisabled && <Text style={styles.second}>{String(second).padStart(2, '0')}</Text>}
          <Text style={[styles.text, countDisabled && styles.disabledText]}>{String(minute).padStart(2, '0')}</Text>
        </View>
        <Button
          onPress={buttonPress}
          style={styles.button}
        >
          <Image source={buttonIcon} />
          <Text style={styles.buttonText}>
            {buttonText}
          </Text>
        </Button>
      </ImageBackground>

      <View style={styles.bottomContainer}>
        <Button
          disabled={buttonDisabled}
          onPress={() => strengthPress(-1)}
        >
          <Text style={[styles.bottomButtonText, buttonDisabled && styles.disabledButtonText]}>-</Text>
        </Button>

        <View style={styles.textContainer}>
          <Text style={[styles.strength, buttonDisabled && styles.disabledText]}>{strength}</Text>
          <Text style={styles.percent}>%</Text>
        </View>

        <Button
          disabled={buttonDisabled}
          onPress={() => strengthPress(1)}
        >
          <Text style={[styles.bottomButtonText, buttonDisabled && styles.disabledButtonText]}>+</Text>
        </Button>
      </View>

      <Text style={[styles.strengthText, buttonDisabled && styles.disabledText]}>刺激强度</Text>

      {isPause && (
      <PauseModal
        visible={isPause}
        pauseCount={pauseCount}
        onEnd={onEnd}
        onContinue={onContinue}
        totalSecond={deviceData.pauseRemainingTimeInSeconds - 1}
      />
      )}

      {pauseLimit && (
      <PauseLimitModal
        visible={pauseLimit}
        onEnd={onEnd}
        onContinue={onContinue}
      />
      )}

      {isFinish && <FinishModal visible={isFinish} remainingCount={leftTreatment} onEnd={onFinish} />}

      {showDeviceMaintenance && <DeviceMaintenance visible={showDeviceMaintenance} onPress={() => setShowDeviceMaintenance(false)} />}
    </View>
  )
}

export default Connected

const styles = EStyleSheet.create({
  page: {
    flex: 1,
    backgroundColor: '$bgColor',
    justifyContent: 'center',
    alignItems: 'center',
  },
  imgBox: {
    width: 252,
    height: 372,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: 105,
    paddingBottom: 77,
    marginBottom: 12,
  },
  textBox: {
    flex: 1,
    justifyContent: 'center',
  },
  second: {
    alignSelf: 'flex-end',
    marginRight: -20,
    marginBottom: -20,
    fontSize: 20,
    fontFamily: 'Avenir-Light',
    fontWeight: '300',
    color: '#8C8C8C',
  },
  text: {
    fontSize: 60,
    fontFamily: 'Avenir-Light',
    fontWeight: '300',
    color: '$fontColor',
    paddingHorizontal: 1,
  },
  disabledText: {
    color: '#DCDCDC',
  },
  button: {
    width: 100,
    height: 46,
    borderRadius: 23,
    borderWidth: 0.5,
    borderColor: '#DCDCDC',
    backgroundColor: '#F3F3F5',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 20,
  },
  buttonText: {
    fontSize: 16,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '$fontColor',
  },
  bottomContainer: {
    flexDirection: 'row',
    width: 252,
    paddingHorizontal: 18,
    alignItems: 'center',
  },
  bottomButtonText: {
    backgroundColor: '#F3F3F5',
    width: 34,
    height: 27,
    borderWidth: 0.5,
    borderColor: '#D0D4DB',
    borderRadius: 14,
    fontSize: 16,
    fontFamily: 'PingFangTC-Medium',
    fontWeight: 'bold',
    color: '#595959',
    textAlign: 'center',
    lineHeight: 26,
  },
  disabledButtonText: {
    borderColor: '$disabled',
    backgroundColor: '#F3F3F5',
    color: '#DCDCDC',
  },
  textContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
  },
  strength: {
    fontSize: 48,
    fontFamily: 'Avenir-Light',
    fontWeight: '300',
    color: '$fontColor',
    paddingHorizontal: 1,
  },
  percent: {
    fontSize: 16,
    fontFamily: 'PingFangSC-Light',
    fontWeight: '300',
    color: '#D0D4DB',
    alignSelf: 'flex-end',
    marginBottom: 12,
  },
  strengthText: {
    fontSize: 16,
    fontFamily: 'PingFangSC-Light',
    fontWeight: '300',
    color: '#8C8C8C',
  },
  errorBox: {
    borderRadius: 17,
    backgroundColor: 'rgba(255,86,0,0.1)',
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    paddingVertical: 8,
  },
  error: {
    fontSize: 14,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '$fontColor',
    paddingLeft: 8,
  },
  headerRight: {
    fontSize: 16,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '#333333',
    paddingRight: 16,
  },
})
